﻿using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GMall.AdministrationService.EntityFrameworkCore
{
    public class AdministrationServiceDbContextFactory : IDesignTimeDbContextFactory<AdministrationServiceDbContext>
    {
        public AdministrationServiceDbContext CreateDbContext(string[] args)
        {
            AdministrationServiceEfCoreEntityExtensionMappings.Configure();

            var configuration = BuildConfiguration();
            
            var builder = new DbContextOptionsBuilder<AdministrationServiceDbContext>()
                .UseMySql(configuration.GetConnectionString(AdministrationServiceDbProperties.ConnectionStringName), MySqlServerVersion.LatestSupportedServerVersion);

            return new AdministrationServiceDbContext(builder.Options);
        }

        private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(
                    Path.Combine(
                        Directory.GetCurrentDirectory(),
                        $"..{Path.DirectorySeparatorChar}GMall.AdministrationService.HttpApi.Host"
                    )
                )
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }
    }
}
